package com.agricultural.machine.chain;

import com.agricultural.machine.common.IMachine;
import com.agricultural.machine.factory.MachineFactory;
import com.agricultural.machine.state.EmergencyStoppedState;


public class EmergencyHandler extends AbstractSafetyHandler {
    private final MachineFactory machineFactory;
    
    public EmergencyHandler() {
        this.machineFactory = MachineFactory.getInstance();
    }
    
    @Override
    public boolean handle(SafetyEvent event) {
        if (event.getEventType().equals("EMERGENCY")) {
            System.out.println("紧急情况处理器处理事件: " + event.getDescription());
            
            // 获取农机
            IMachine machine = machineFactory.getMachine(event.getMachineId());
            if (machine == null) {
                System.out.println("无法找到农机: " + event.getMachineId());
                return false;
            }
            
            // 紧急停止
            machine.setEmergencyStop(true);
            machine.setState(new EmergencyStoppedState());
            
            System.out.println("农机 " + machine.getMachineId() + " 已紧急停止");
            
            // 根据紧急情况类型处理
            String emergencyType = event.getEventData();
            switch (emergencyType) {
                case "COLLISION":
                    handleCollisionEmergency(machine);
                    break;
                case "BOUNDARY":
                    handleBoundaryEmergency(machine);
                    break;
                case "WEATHER":
                    handleWeatherEmergency(machine);
                    break;
                default:
                    System.out.println("处理未知紧急情况: " + emergencyType);
                    break;
            }
            
            // 标记事件已处理
            event.setHandled(true);
            return true;
        }
        
        // 不是紧急情况事件，传递给下一个处理器
        return handleNext(event);
    }
    

    private void handleCollisionEmergency(IMachine machine) {
        System.out.println("处理碰撞紧急情况");
        System.out.println("向控制中心发送碰撞警报");
        System.out.println("启动远程诊断程序");
        System.out.println("等待操作员确认");
    }
    

    private void handleBoundaryEmergency(IMachine machine) {
        System.out.println("处理边界紧急情况");
        System.out.println("记录当前位置");
        System.out.println("发送边界越界通知");
        System.out.println("等待操作员指示");
    }
    
    /**
     * 处理天气紧急情况
     */
    private void handleWeatherEmergency(IMachine machine) {
        System.out.println("处理恶劣天气紧急情况");
        System.out.println("收集当前天气数据");
        System.out.println("计算安全撤离路线");
        System.out.println("建议操作员暂停所有作业");
    }
} 